'use client';
import {createPatch} from 'diff';
import {parse} from 'diff2html';
import {DiffFile} from 'diff2html/lib/types';
import dynamic from 'next/dynamic';
import {useCallback, useMemo, useState} from 'react';
import {Stack} from 'react-bootstrap';
import Loading from '@/app/loading';
import useDebounce from '@/components/hook/useDebounce';
import {Func} from '@/types/utils';
import style from './style.module.scss';

const DiffView = dynamic(
    () => import('./DiffView'),
    {ssr: false, loading: () => <Loading></Loading>}
);

function HomeIndex() {
    const [lText, setLText] = useState('');
    const [rText, setRText] = useState('');
    const debounce = useDebounce(500);

    const handleChange = useCallback((value: string, label: string) => {
        debounce(() => {
            const handleMap: Record<string, Func> = {
                l: () => setLText(value),
                r: () => setRText(value)
            };
            handleMap[label] && handleMap[label]();
        });
    }, [debounce]);

    const diffFile = useMemo<DiffFile[]>(() => {
        const diffStr = createPatch('', lText, rText, '', '');
        return parse(diffStr);
    }, [lText, rText]);

    return <div className={style['diff-root-wrapper']}>
        <div className={style['swiper-wrapper']}>
            <Stack direction='horizontal' gap={3} className={style['textarea-group']}>
                <textarea className={style['textarea']} onChange={e => handleChange(e.target.value, 'l')} />
                <textarea className={style['textarea']} onChange={e => handleChange(e.target.value, 'r')} />
            </Stack>
            <DiffView diffFile={diffFile} />
        </div>
    </div>;
}

export default HomeIndex;
